import json

import requests

openid = "xxx"
apikey = "xxx"


def dxx():
    course_url = "http://qndxx.cqyouths.com/new_course.json"
    study_course_url = fr"http://qndxx.cqyouths.com/api/course/studyCourse?openid={openid}&id="
    res_course = request_get(course_url)
    if res_course:
        class_id = res_course['data'][0]['id']
        study_course_url += str(class_id)
        res_study_course = request_get(study_course_url)
        if res_study_course:
            send_msg("学习最新大学习成功: <" + res_course['data'][0]['name'] + '>', 'ok')
            print("学习最新大学习成功: <" + res_course['data'][0]['name'] + '>' + res_course['data'][0]['link'])
        else:
            send_msg("学习最新大学习失败: <" + res_course['data'][0]['name'] + '>', "学习失败" + json.dumps(res_study_course))
            print("学习失败" + json.dumps(res_study_course) + res_course['data'][0]['link'])
    else:
        send_msg("请求新课程失败 status 不为200", 'error')
        print("请求新课程失败 status 不为200")


def request_get(url):
    res = requests.get(url)
    if res.status_code == 200:
        content = res.content.decode("utf-8")
        res_json = json.loads(content)
        return res_json
    else:
        return False


def send_msg(title, content):
    url = fr"https://sctapi.ftqq.com/{apikey}.send?title={title}&desp={content}"
    request_get(url)


dxx()
